package com.affectu.dao.pagination;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.hibernate.search.FullTextQuery;
import org.hibernate.search.FullTextSession;

import com.affectu.category.Category;
import com.affectu.common.util.PersistanceUtil;
import com.affectu.search.LuceneUtil;
import com.affectu.task.InnerTask;
import com.affectu.task.OuterTask;
import com.affectu.task.Task;

/**
 * Oct 13, 2008
 * 
 * @author daniel nathan
 */
public class CategoryTaskDataModel extends BaseDataModel<Task, Long> {

    private FullTextSession fs = PersistanceUtil.getInstance().getFullTextSession();

    private Category category;

    private static String[] taskFields = { "tag" };

    private static LuceneUtil luceneUtil = LuceneUtil.getInstance();

    public CategoryTaskDataModel(Category category) {
        this.category = category;
    }

    @Override
    public Task findById(Long id) {
        return (Task) fs.get(Task.class, id);
    }

    @Override
    public Long getCount() {
        Long count = 0L;
        FullTextQuery ftQuery = null;
        try {
            ftQuery = fs.createFullTextQuery(luceneUtil.getLuceneQuery(taskFields, this.getTagsWithBlank()), InnerTask.class,
                    OuterTask.class);
            count = Long.valueOf(ftQuery.getResultSize());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Task> getList(Integer firstRow, Integer maxResults) {
        List<Task> resultList = new ArrayList<Task>();
        FullTextQuery ftQuery = null;
        try {
            ftQuery = fs.createFullTextQuery(luceneUtil.getLuceneQuery(taskFields, this.getTagsWithBlank()), InnerTask.class,
                    OuterTask.class).setFirstResult(firstRow).setMaxResults(maxResults);
            Sort sort = new Sort(new SortField("id", SortField.AUTO, true));
            ftQuery.setSort(sort);
            resultList = ftQuery.list();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return resultList;
    }

    private String getTagsWithBlank() {
        List<Category> children = category.getChildren();
        String tags = "";
        for (int i = 0; i < children.size(); i++) {
            tags += "" + children.get(i).getName() + " ";
        }
        tags += "" + category.getName() + " ";
        return tags;
    }

    public void finalize() {
        fs.close();
    }

    public void destroy() {
        fs.close();
    }
}
